package com.gupao.rpc.protocol.spring.reference;

import com.gupao.rpc.protocol.annotation.RpcRemoteReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class SpringRpcReferencePostProccessor implements ApplicationContextAware, BeanClassLoaderAware, BeanFactoryPostProcessor {
    private ClassLoader classLoader;
    private ApplicationContext applicationContext;
    private RpcClientProperties properties;

    private Map<String, BeanDefinition> rpcReferenceDefinitionMap = new ConcurrentHashMap<>();

    public SpringRpcReferencePostProccessor(RpcClientProperties properties) {
        this.properties = properties;
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDefinitionName);
            String beanClassName = beanDefinition.getBeanClassName();
            if (beanClassName != null) {
                Class<?> clazz = ClassUtils.resolveClassName(beanClassName, this.classLoader);
                ReflectionUtils.doWithFields(clazz, this::parseRpcReference);
            }
        }
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        this.rpcReferenceDefinitionMap.forEach((beanName, beanDefinition) -> {
            if (applicationContext.containsBean(beanName)) {
                log.warn("------->>>> springContext has register bean {}", beanName);
                return;
            }
            registry.registerBeanDefinition(beanName, beanDefinition);
            log.info("------->>>> register rpcReferenceBean {} success", beanName);
        });

    }

    private void parseRpcReference(Field field) {
        RpcRemoteReference annotation = AnnotationUtils.getAnnotation(field, RpcRemoteReference.class);
        if (annotation != null) {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(SpringRpcReferenceFactoryBean.class);
            builder.setInitMethodName("init");
            builder.addPropertyValue("classInterfaces", field.getType());
            builder.addPropertyValue("host", this.properties.getHost());
            builder.addPropertyValue("port", this.properties.getPort());
            BeanDefinition beanDefinition = builder.getBeanDefinition();
            this.rpcReferenceDefinitionMap.put(field.getName(), beanDefinition);
        }
    }

}
